# -*- coding:utf-8 -*-

from XlsFileUtil import XlsFileUtil
import os


"""
解析表头为文件夹
"""
def readName(folderPath, val):
    name = val.split("(")[1]
    name = name.split(")")[0]
    langFolderPath = ""
    if folderPath.endswith("/"):
        langFolderPath = folderPath + name + ".lproj"
    else:
        langFolderPath = folderPath + "/" + name + ".lproj"
    
    print "colName:%s foldName:%s path:%s" % (val, name, langFolderPath)
    # 如果文件夹不存在，则生成
    if not os.path.exists(langFolderPath):
        os.makedirs(langFolderPath)
    filePath = langFolderPath + "/Localizable.strings"
    return filePath

"""
解析每一个列文多语言文件
"""
def readCols(targetDir, sheet, colIndex):
     # 读取每一行
    iosFileManager = None
    for rowIndex, row in enumerate(sheet.get_rows()):
        if rowIndex == 0:
            LocalizablePath = readName(targetDir, row[colIndex].value)
            if os.path.exists(LocalizablePath):
                #删除文件,path为文件路径
                os.remove(LocalizablePath)
            # 开启读文件
            iosFileManager = open(LocalizablePath, "wb")
        else:
            strKey = row[1].value
            strVal = row[colIndex].value
            print "strKey:%s strVal:%s" % (strKey, strVal)
            if(not strKey):
                # 没有key的行为注释行
                moduleName = row[0].value
                content = "\n// " + moduleName + "\n"
                iosFileManager.write(content)
            else:
                # 内容行
                content = "\"" + strKey + "\" " + "= " + "\"" + strVal + "\";\n"
                iosFileManager.write(content)
    # 保存关闭
    iosFileManager.close()
    print "end converting"

def startConvert(xlsxPath, targetDir):
    print "Start converting"

    if xlsxPath is None:
        print "xls files directory can not be empty! try -h for help."
        return

    if targetDir is None:
        print "Target file directory can not be empty! try -h for help."
        return

     # 解析xls
    xlsFileUtil = XlsFileUtil(xlsxPath)
    
    # 读取所有tab
    sheet = xlsFileUtil.getAllTables()[0]
    colCount = sheet.ncols
    print "colCount: %d" % (colCount)
    for colIndex in range(2, colCount):
        print "colIndex: %d" % (colCount)
        readCols(targetDir, sheet, colIndex)
    print "end converting"
        


def main():
    # 解析参数
    xlsxPath = "examples/helloi18n.xlsx"
    targetDir = "examples/output/ios/i18n"
    # 开始转换
    startConvert(xlsxPath, targetDir)
# python python/xlsx2string.py

main()
